package com.atguigu.servlet;

import com.atguigu.constant.OrderStatus;
import com.atguigu.domain.Cart;
import com.atguigu.domain.Order;
import com.atguigu.domain.User;
import com.atguigu.service.OrderService;
import com.atguigu.service.impl.OrderServiceImpl;
import com.atguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author dl
 * @date 2020/5/4 18:55
 */
@WebServlet(name = "UserOrderServlet",urlPatterns = "/user/order")
public class UserOrderServlet extends BaseServlet {

    private OrderService orderService = new OrderServiceImpl();

    /**
     * 用户结账
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void checkout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        // 用户已经登录
        Cart cart = (Cart) session.getAttribute("cart");
        String orderId = orderService.checkout(cart, user);
        session.setAttribute("orderId",orderId);
        resp.sendRedirect(req.getContextPath() + "/pages/cart/checkout.jsp");
    }

    /**
     * 用户查看订单列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        User user = WebUtils.getLoginUser(req);
        if (user == null) {
            // 用户没有登录
            req.setAttribute("msg","当前操作需要登录才能进行");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            return;
        }
        // 用户已经登录
        List<Order> list = orderService.getOrder(user.getId().toString());
        session.setAttribute("orders",list);
        req.getRequestDispatcher("/pages/order/order.jsp").forward(req,resp);
    }

    /**
     * 用户查看订单列表
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void updateStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderId = req.getParameter("orderId");
        orderService.update(orderId, OrderStatus.COMPLETE.toString());
        String referer = req.getHeader("Referer");
        resp.sendRedirect(referer);
    }


}
